package com.zhiyou100.crm.servlet.user;

import com.zhiyou100.crm.pojo.User;
import com.zhiyou100.crm.service.UserService;
import com.zhiyou100.crm.service.impl.UserServiceImpl;



import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
       
	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		//获取文本框输入的内容
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Cookie cookie=new Cookie("admin",username);
		Cookie cookie1=new Cookie("password",password);
		cookie.setPath("/");
		cookie.setMaxAge(Integer.MAX_VALUE);
		response.addCookie(cookie);
		cookie1.setPath("/");
		cookie1.setMaxAge(Integer.MAX_VALUE);
		response.addCookie(cookie1);
		PrintWriter out=response.getWriter();
		UserService userService =new UserServiceImpl();
		List<User> users1 = userService.queryAllUser();
		List<User> users=new ArrayList<>();
		if(users1!=null){
			if (username != null && password != null && password != ""&&username!=null) {
				for (int i = 0; i < users1.size(); i++) {
					if(users1.get(i).getUsername().equals(username)){
						users.add(users1.get(i));
						break;
					}
				}
				if (password.equals(users.get(0).getPassword()) ){
					request.getSession().setAttribute("user",users.get(0));
					response.sendRedirect(request.getContextPath() + "/admin.jsp");
				} else {
					request.setAttribute("errorMessage", "密码错误！");
					request.getRequestDispatcher("/index.jsp").forward(request, response);
				}
			} else if (password == null || password == "") {
				request.setAttribute("errorMessage", "密码不能为空！");
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}
		} else {
			request.setAttribute("errorMessage", "该用户名不存在！");
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		}
	}

}
